/**
 * 
 */
package com.sys.object.common.utils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.springframework.util.StringUtils;

import com.sys.object.common.context.Config;

/**
 * created 2011-10-24
 * 
 * @author friend
 * 
 */
public class DateUtils {

	public static String getYearMothDate() {
		return "" + (getCurYear() + getCurMonth() + getCurDay());
	}
	
	public static String getYearMothDateFolder() {
		return getCurYear() +"/"+ getCurMonth() +"/"+ getCurDay();
	}

	/**
	 * 获得当前年份
	 */

	public static String getCurYear() {
		GregorianCalendar gcDate = new GregorianCalendar();
		return "" + gcDate.get(GregorianCalendar.YEAR);
	}

	/**
	 * 获得当前月
	 */
	public static String getCurMonth() {
		GregorianCalendar gcDate = new GregorianCalendar();
		int month = (gcDate.get(GregorianCalendar.MONTH)) + 1;
		String temp = "";
		if (month < 10) {
			temp = "0" + month;
		} else {
			temp = "" + month;
		}
		if ("00".equals(temp)) {
			temp = "12";
		}
		return temp;
	}

	/**
	 * 获得当前日期
	 */
	public static String getCurDay() {
		GregorianCalendar gcDate = new GregorianCalendar();
		return "" + gcDate.get(GregorianCalendar.DAY_OF_MONTH);
	}

	/**
	 * 获得当前日期
	 */
	public static String getCurDate_() {
		GregorianCalendar gcDate = new GregorianCalendar();
		int year = gcDate.get(GregorianCalendar.YEAR);
		int month = gcDate.get(GregorianCalendar.MONTH) + 1;
		int day = gcDate.get(GregorianCalendar.DAY_OF_MONTH);

		return year + "-" + month + "-" + day;
	}

	public static String getCurDatehhmmss_() {
		GregorianCalendar gcDate = new GregorianCalendar();
		int year = gcDate.get(GregorianCalendar.YEAR);
		int month = gcDate.get(GregorianCalendar.MONTH) + 1;
		int day = gcDate.get(GregorianCalendar.DAY_OF_MONTH);
		int hh = gcDate.get(GregorianCalendar.HOUR_OF_DAY);
		int mm = gcDate.get(GregorianCalendar.MINUTE);
		int ss = gcDate.get(GregorianCalendar.SECOND);
		return year + "-" + month + "-" + day + " " + hh + ":" + mm + ":" + ss;
	}

	/**
	 * 获得当前日期
	 */
	public static String getCurDate_(int daybefore) {
		GregorianCalendar gcDate = new GregorianCalendar();
		int year = gcDate.get(GregorianCalendar.YEAR);
		int month = gcDate.get(GregorianCalendar.MONTH) + 1;
		int day = gcDate.get(GregorianCalendar.DAY_OF_MONTH);

		return year + "-" + month + "-" + (day + daybefore);
	}

	/**
	 * 获取当前周几
	 * 
	 * @return
	 */
	public static Integer getCurWeek() {
		GregorianCalendar gcDate = new GregorianCalendar();
		int week = gcDate.get(Calendar.WEEK_OF_YEAR);
		return week;
	}

	/**
	 * 将字符串转换成日期
	 */
	public static Date convertStr2Date(String dateStr) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return format.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
			throw new RuntimeException("日期转换异常");
		}
	}

	/**
	 * 将字符串转换成日期
	 */
	public static Date convertStr2Date_hh_mm(String dateStr) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			return format.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
			throw new RuntimeException("日期转换异常");
		}
	}

	public static Date convertStr2Date_hh_mm_ss(String dateStr) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return format.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
			throw new RuntimeException("日期转换异常");
		}
	}

	public static Date strToDate(String date) {
		try {
			if (StringUtils.hasText(date)) {
				date = date.replaceAll("年", "-").replaceAll("月", "-").replaceAll("日", "").replaceAll("\\/", "-");
				return convertStr2Date_hh_mm_ss(date);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Date strToDateFromCell(String str) {
		try {
			Double cellint = Double.valueOf(str);
			Date date = new Date(0);
			date = HSSFDateUtil.getJavaDate(new Double(cellint));
			// SimpleDateFormat simpleDateFormat = new
			// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			// date = simpleDateFormat.f.parse(date);]
			return date;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static long convertStrToLong(String dateStr) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return format.parse(dateStr).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
			throw new RuntimeException("日期转换异常");
		}
	}

	public static long convertDataTimeToLong(String dateStr) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			return format.parse(dateStr).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
			throw new RuntimeException("日期转换异常");
		}
	}

	public static long convertStrToLong() {
		try {
			return new Date().getTime();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("日期转换异常");
		}
	}

	public static int convertStrToInt() {
		try {
			return (int) (new Date().getTime() / 1000);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("日期转换异常");
		}
	}

	public static long convertStrToLongYYYYMMDD(String dateStr) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return format.parse(dateStr).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
			throw new RuntimeException("日期转换异常");
		}
	}

	public static Timestamp convertStr2Timestamp_hh_mm(String dateStr) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			Date date = convertStr2Date_hh_mm(dateStr);
			return new Timestamp(date.getTime());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("日期转换异常");
		}
	}

	public static Timestamp convertStr2Timestamp_hh_mm_ss(String dateStr) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date date = convertStr2Date_hh_mm_ss(dateStr);
			return new Timestamp(date.getTime());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("日期转换异常");
		}
	}

	/**
	 * 将日期转换成如：2010-08-08 12:00
	 */
	public static String foramteDate_hh_mm(Date date) {
		if (!(date instanceof Date) && date == null) {
			return null;
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		return format.format(date);
	}

	/**
	 * 将日期转换成如：2010-08-08 12:00
	 */
	public static String foramteDate(Date date) {
		if (!(date instanceof Date) && date == null) {
			return null;
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		return format.format(date);
	}

	/**
	 * 将日期转换成如：2010-08-08 12:00
	 */
	public static String foramteDate_curDate(Date date) {
		if (!(date instanceof Date) && date == null) {
			return null;
		}
		Long times = date.getTime() - (24 * 60 * 60 * 1000);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		return format.format(new Date(times));
	}

	public static String foramteDate_hh_mm_ss(Date date) {
		if (!(date instanceof Date) && date == null) {
			return null;
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(date);
	}

	/**
	 * 返回两个日期相差的天数
	 */
	public static int diff_in_date(Date d1, Date d2) {
		return (int) (d1.getTime() - d2.getTime()) / 86400000;
	}

	/**
	 * 返回服务器当时时间戳
	 * 
	 * @return
	 */
	public static long ServerTimeMillis() {
		return System.currentTimeMillis();
	}

	/**
	 * 判断字符串类型的两个日期date1是否大于date2
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static boolean compareDate(String date1, String date2) {
		// if (StringUtils.isBlank(date1) && StringUtils.isBlank(date2)) {
		// 1408550398
		// throw new RuntimeException("做比较的两个日期不能为空");
		// }
		Date d1 = DateUtils.convertStr2Date_hh_mm(date1);
		Date d2 = DateUtils.convertStr2Date_hh_mm(date2);
		int d = DateUtils.diff_in_date(d1, d2);
		return d > 0 ? true : false;

	}

	public static String getFileDate(String path) {
		if (path.indexOf("2") != -1) {
			String str = path.substring(path.indexOf("2"), path.indexOf("_"));
			// char[] c = str.toCharArray();
			String s = str.substring(0, 4) + "-" + str.substring(4, 6) + "-" + str.substring(6, str.length())
					+ " 00:00:00";
			return s;
		}
		return "";
	}

	public static String getDateLastTime() {
		return getCurDate_() + " 23:59:59";
	}

	public static String getDateLastTime(String date) {
		return date + " 23:59:59";
	}

	public static String getDateStartTime(String date) {
		return date + " 00:00:00";
	}

	public static String getUserAge(String age) {
		try {
			if (StringUtils.hasText(age)) {
				String[] str = age.split("-");
				String[] nowdate = getCurDate_().split("-");
				int ages = 0;
				if (Integer.parseInt(nowdate[1]) - Integer.parseInt(str[1]) > 0) {
					ages += 1;
				}
				if (Integer.parseInt(nowdate[0]) - Integer.parseInt(str[0]) <= 0) {
					return "0";
				}
				ages += Integer.parseInt(nowdate[0]) - Integer.parseInt(str[0]);
				return ages + "";
			}
			return "0";
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}

	public static String currentTimeMillisToDatestr(int times) {
		if (times > 0) {
			long t = (times * 1000l);// Long.parseLong(times+"");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dates = sdf.format(new Date(t));
			return dates;
		}
		return "";
	}

	public static String currentTimeMillisToDatestrYYYYMMDD(int times) {
		if (times > 0) {
			long t = Long.parseLong(times + "");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String dates = sdf.format(new Date(t * 1000));
			return dates;
		}
		return "";
	}

	public static Long[] stringToLong(String str) {
		if (StringUtils.hasText(str)) {
			String[] ss = str.split(",");
			Long[] lo = new Long[ss.length];
			for (int i = 0; i < ss.length; i++) {
				lo[i] = Long.parseLong(ss[i]);
			}
			return lo;
		}
		return null;
	}

	public static Integer[] stringToInteger(String str) {
		if (StringUtils.hasText(str)) {
			String[] ss = str.split(",");
			Integer[] lo = new Integer[ss.length];
			for (int i = 0; i < ss.length; i++) {
				lo[i] = Integer.parseInt(ss[i]);
			}
			return lo;
		}
		return null;
	}

	public static String CalcTime(long posttime) {
		posttime = posttime * 1000;
		long currtime = System.currentTimeMillis();
		long realtime = currtime - posttime;
		long zero = posttime - getTodayZero();
		if (realtime <= 0 || zero == 0) {
			return "刚刚";
		}
		int miao = (int) (realtime / 1000);
		if (miao < 60 && miao > 0) {
			return miao + "秒前";
		}
		int min = (int) (realtime / 1000 / 60);
		if (min > 60) {
			if (zero < 0) {
				int yeHour = (int) (Math.abs(zero) / 1000 / 60 / 60);
				if (yeHour < 24) {
					return "昨日" + new SimpleDateFormat("HH:MM").format(new Date(posttime));
				} else {
					return new SimpleDateFormat("MM-dd").format(new Date(posttime));
				}
			} else {
				return new SimpleDateFormat("HH:MM").format(new Date(posttime));
			}
		} else {
			if (min < 1)
				return "刚刚";

			return min + "分钟前";
		}
	}

	public static long getTodayZero() {
		Calendar calendar = Calendar.getInstance();
		int day = calendar.get(Calendar.DAY_OF_YEAR);

		calendar.set(Calendar.DAY_OF_YEAR, day);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		return (calendar.getTimeInMillis());
	}

	/**
	 * 取本周7天的第一天（周一的日期）
	 */
	public static String getNowWeekBegin(Date date) {
		int mondayPlus;
		Calendar cd = Calendar.getInstance();
		cd.setTime(date);
		// 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
		int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1; // 因为按中国礼拜一作为第一天所以这里减1
		if (dayOfWeek == 1) {
			mondayPlus = 0;
		} else {
			mondayPlus = 1 - dayOfWeek;
		}
		GregorianCalendar currentDate = new GregorianCalendar();
		currentDate.add(GregorianCalendar.DATE, mondayPlus);
		Date monday = currentDate.getTime();

		DateFormat df = DateFormat.getDateInstance();
		String preMonday = df.format(monday);

		return preMonday;
	}

	/**
	 * 根据周日获取周一日期
	 * 
	 * @param date
	 * @return
	 */
	public static String getWeekBeginMonday(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cd = Calendar.getInstance();
		cd.setTime(date);

		cd.add(GregorianCalendar.DATE, -6);

		return format.format(cd.getTime());
	}

	/**
	 * 获取每月的第一天
	 * 
	 * @param date
	 * @return
	 */
	public static String getMonthBegin(Date date) {

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

		Calendar calendar = Calendar.getInstance();// 获取当前日期
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
		return format.format(calendar.getTime());
	}

	/**
	 * 获取两个日期之间所有的月份的最后一天
	 * 
	 * @param minDate
	 * @param maxDate
	 * @return
	 * @throws ParseException
	 */
	public static List<String> getMonthBetween(String minDate, String maxDate) throws ParseException {
		ArrayList<String> result = new ArrayList<String>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 格式化为年月

		Calendar min = Calendar.getInstance();
		Calendar max = Calendar.getInstance();

		min.setTime(sdf.parse(minDate));
		min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

		max.setTime(sdf.parse(maxDate));
		max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

		Calendar curr = min;
		while (curr.before(max)) {
			// 设置日期为本月最大日期
			curr.set(Calendar.DATE, curr.getActualMaximum(Calendar.DATE));
			result.add(sdf.format(curr.getTime()));
			curr.add(Calendar.MONTH, 1);
		}

		return result;
	}

	public static String dateToCron(String date) {
		if (StringUtils.hasText(date)) {
			// Date da = convertStr2Date_hh_mm(date);
			GregorianCalendar da = convertStrGregorianCalendarhhmmss(date);
			return "0 " + da.get(GregorianCalendar.MINUTE) + " " + da.get(GregorianCalendar.HOUR_OF_DAY) + " "
					+ da.get(GregorianCalendar.DAY_OF_MONTH) + " " + (da.get(GregorianCalendar.MONTH) + 1) + " ? "
					+ (da.get(GregorianCalendar.YEAR));
		}
		return null;
	}

	public static GregorianCalendar convertStrGregorianCalendarhhmmss(String dateStr) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			Date date = format.parse(dateStr);
			date = new Date(date.getTime());
			GregorianCalendar calendar = new GregorianCalendar();
			calendar.setTime(date);
			return calendar;
		} catch (ParseException e) {
			e.printStackTrace();
			throw new RuntimeException("日期转换异常");
		}
	}

	public static Integer createValYear(String fromDate, String toDate) {
		if (StringUtils.hasText(fromDate) && StringUtils.hasText(toDate)) {
			Calendar beginCalendar = Calendar.getInstance();
			Calendar endCalendar = Calendar.getInstance();
			beginCalendar.setTime(convertStr2Date(fromDate));
			endCalendar.setTime(convertStr2Date(toDate));
			int y = endCalendar.get(Calendar.YEAR) - beginCalendar.get(Calendar.YEAR);
			if(y<1)
				y = 1;
			return y;
		}
		return null;
	}

	public static Integer createValYear(Date fromDate, Date toDate) {
		if (fromDate != null && toDate != null) {
			Calendar beginCalendar = Calendar.getInstance();
			Calendar endCalendar = Calendar.getInstance();
			beginCalendar.setTime(fromDate);
			endCalendar.setTime(toDate);
			int y = endCalendar.get(Calendar.YEAR) - beginCalendar.get(Calendar.YEAR);
			if(y<1)
				y = 1;
			return y;
		}
		return null;
	}

	/**
	 * c1证有效日期的cron规则 通过配置config.properties设置测试的cron，当前时间后的多少分钟
	 * 
	 * @param validdate
	 * @param day
	 * @return
	 */
	public static String dateToCronByc1(Date validdate, int day) {
		String testCron = Config.getConfigValue("quartz_test_cron");
		if (StringUtils.hasText(testCron)) {
			String[] args = testCron.split(":", -1);
			if (args.length == 2) {
				if (Boolean.valueOf(args[0])) {
					/**
					 * 测试的cron
					 */
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					Long time = System.currentTimeMillis() + (Integer.valueOf(args[1]) * 60 * 1000);
					String nowdate = format.format(new Date(time));
					GregorianCalendar da = convertStrGregorianCalendarhhmmss(nowdate);
					return "0 " + da.get(GregorianCalendar.MINUTE) + " " + da.get(GregorianCalendar.HOUR_OF_DAY) + " "
							+ da.get(GregorianCalendar.DAY_OF_MONTH) + " " + (da.get(GregorianCalendar.MONTH) + 1)
							+ " ? " + (da.get(GregorianCalendar.YEAR));
				}
			}
		}
		/**
		 * 正式的cron
		 */
		if (validdate!=null) {
			Long time = validdate.getTime() - (day * 24 * 60 * 60 * 1000l)+(10*60*60*1000l);
			GregorianCalendar da = new GregorianCalendar();
			da.setTime(new Date(time));
			System.out.println("cron>>>"+"0 " + da.get(GregorianCalendar.MINUTE) + " " + da.get(GregorianCalendar.HOUR_OF_DAY) + " "+ da.get(GregorianCalendar.DAY_OF_MONTH) + " " + (da.get(GregorianCalendar.MONTH) + 1) + " ? "+ (da.get(GregorianCalendar.YEAR)));
			return "0 " + da.get(GregorianCalendar.MINUTE) + " " + da.get(GregorianCalendar.HOUR_OF_DAY) + " "
					+ da.get(GregorianCalendar.DAY_OF_MONTH) + " " + (da.get(GregorianCalendar.MONTH) + 1) + " ? "
					+ (da.get(GregorianCalendar.YEAR));
		}
		return null;

	}

	public static Date getC1Valid(Date date) {
		Long time = ((date.getTime() + (3 * 365 * 24 * 60 * 60 * 1000l)));
		return new Date(time);
	}

	public static Date getC1Valid(String dates) {
		Date date = convertStr2Date_hh_mm_ss(dates);
		return getC1Valid(date);
	}
	
	public static Date excelValueToDate(String date){
		date = date.replaceAll("年", "-").replaceAll("月", "").replaceAll("日", "");
		if(date.indexOf(".")!=-1){
			date = date.replaceAll("\\.", "-");
			return convertStr2Date_hh_mm_ss(date);
		}else if(date.indexOf("/")!=-1){
			date = date.replaceAll("\\/", "-");
			return convertStr2Date_hh_mm_ss(date);
		}
		else if(date.indexOf("-")!=-1){
			return convertStr2Date_hh_mm_ss(date);
		}
		else if(Rule.isNumeric(date)){
			return DateUtils.strToDateFromCell(date);
		}else{
			return new Date();
		}
		
	}

	/**
	 * 获取两个日期之间所有的星期天
	 * 
	 * @param minDate
	 * @param maxDate
	 * @return
	 * @throws ParseException
	 */
	public static List<String> getWeeksBetween(String minDate, String maxDate) throws ParseException {
		ArrayList<String> result = new ArrayList<String>();
		Calendar min = Calendar.getInstance();
		Calendar max = Calendar.getInstance();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 格式化为年月

		DateFormatSymbols dfs = new DateFormatSymbols();
		String[] weeks = dfs.getWeekdays();

		min.setTime(sdf.parse(minDate));
		min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), min.get(Calendar.DAY_OF_MONTH));

		max.setTime(sdf.parse(maxDate));
		max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), max.get(Calendar.DAY_OF_MONTH));

		max.add(Calendar.DAY_OF_YEAR, 1); // 结束日期下滚一天是为了包含最后一天

		while (min.before(max)) {
			// System.out.println("=========="+new
			// java.sql.Date(min.getTime().getTime())+"==================");
			if (min.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
				result.add(sdf.format(min.getTime().getTime()));
			}
			min.add(Calendar.DAY_OF_YEAR, 1);
		}

		return result;
	}

	public static void main(String[] arg) {
		// 2013-10-04 00:19:44 1409124953 2014-08-27

		// System.out.println(DateUtils.convertStrToLong("2015-11-06
		// 00:00:00")/1000);
		System.out.println(dateToCronByc1(convertStr2Date_hh_mm_ss("2020-10-11 00:00:00"),240)+"==="+foramteDate_curDate(new Date()));

	}
}
